#!/usr/bin/python
#
# Copyright (C) 2008 rambla.be
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

""" Demo that uses the RATS python client libs to upload a src file, create a transcoding job for it, wait for the job to finish, process the results and download the transcoded file. """

import time
import rawsc
import rawsc.service
from rawsc import rats
import rawsc.rats.service
try:
  from xml.etree import cElementTree as ElementTree
except ImportError:
  try:
    import cElementTree as ElementTree
  except ImportError:
    from elementtree import ElementTree

USER = "XXX"
PWD = "XXX"
SERVER = "rats.enc01.rambla.be"

SRC_FILENAME = "southern_rock_opera.mp4"
TGT_FILENAME = "white_noise.mp4"
LOCAL_FILE = "PATH_TO_LOCAL_SRC_FILE"
LOCAL_TRANSCODINGS_DIR = "PATH_TO_WRITABLE_DIR"
FORMAT_PROFILE = "XXX"
OUTPUT_PROFILE = "XXX"

try:
    # Create a Rass instance, passing it your login credentials and the base service uri
    client = rawsc.rats.service.RatsService(username=USER, password=PWD, server=SERVER)

    # upload the src file, creating an "src" instance
    src_entry = client.createSrc(filename = SRC_FILENAME, local_path = LOCAL_FILE)
    src_location = src_entry.id.text
    src_filename = src_entry.content.params.filename.text
    print "Uploaded a src file:"
    print "src location: %s\n" % src_location

    # create a job, using the filename of the "src" file and a fixed format + output profile
    # NOTE: always use the src_filename from the src entry (returned by RATS when the src is created) 
    #       since RATS may have modified the original src filename (if a file with the same name already exists)
    job_entry = client.createJob(format = FORMAT_PROFILE, output = OUTPUT_PROFILE, src_location = src_filename, tgt_location = TGT_FILENAME)
    job_location = job_entry.id.text
    job_profile_id = job_entry.content.params.id.text
    print "Created a job:"
    print "job location: %s\n" % job_location

    print "Waiting for the job to be done: \n";
    # run a loop, polling the created job until it is finished
    job_status = rawsc.REQUEST_RECEIVED
    while (job_status < rawsc.FINISHED):
        job_entry = client.getJob(job_location)
        job_status = int(job_entry.content.params.status.text)
        print "Polling job " + str(job_profile_id) + ". Status= " + job_entry.content.params.status.text + "\n"
        if job_status >= rawsc.FINISHED:
            if job_status == rawsc.FINISHED:
                print "Job has succeeded, trying to retrieve the URI's...\n";
                for job in job_entry.reports.report.job:
                    if job.action == "transcoding":
                        if job.local_uri:
                            print "Transcoded file available on the RATS Server = '%s'\n" % job.local_uri.text
                    if job.action == "export":
                        if job.public_uri:
                            print "Exported file URI = '%s'\n" % job.public_uri.text
            else:
                print "Job has failed with status code = " + job_entry.content.params.status.text + "\n";
                for job in job_entry.reports.report.job:
                    print "%s job msg = %s\n" % (job.action, job.msg.text)
        else:
            time.sleep(3)

    # download the transcoded file
    if job_status == rawsc.FINISHED or job_status == EXPORT_FAILED:
        # get the transcoded file's filename on the RATS server -> using it to generate a local path to the file
        transc_entry = client.getTransc(job_entry.content.params.transc.text)
        local_transc_path = LOCAL_TRANSCODINGS_DIR + transc_entry.content.params.filename.text
        print "Transcoded file will be downloaded to : %s\n" % local_transc_path;
        # download the file
        client.getTranscFile(uri = job_entry.content.params.transc_media.text, local_path = local_transc_path)

    # (optional) src not longer needed on the RATS server, delete it
    client.delete(src_entry.id.text)

except rawsc.service.Error, e:
    print "Error Response from server, contents = %s.\n" % str(e)
    error_dict = e[0] # error dict inside the first tuple elem
    print "status code : " + str(error_dict["status"]) + "\n"
    if error_dict.has_key("body"):
        print "error body : " + error_dict["body"] + "\n"
except rawsc.RawscException, e:
    print "RawscException caught, reason = %s.\n" % str(e)
except StandardError, e:
    print "StandardError caught, reason = %s.\n" % str(e)
except:
    print "unhandled exception caught\n"
